<template>
    <div id="activity">
        <!--工具栏目-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
            <el-form :inline="true" :model="ActData">
                <el-form-item>
                    <el-input type="number" min="0" v-model="ActData.id" placeholder="请输入要搜索的ID"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="ActData.title" placeholder="请输入要搜索的标题"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getActivity">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="dynamicShowDialogVisible = true">查看动态活动链接</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-alert
                type="info"
                title="定制性的功能，比如：签到有礼、解套、邀请有礼，请单独添加活动并且选择‘打开连接’填写对应的活动地址即可"
                show-icon
                style="margin-bottom: 10px;">
        </el-alert>
        <el-alert
                type="info"
                title="活动时间请向后延迟一天，因为活动选择的时间是没有小时和分钟，比如选择2018年2月20日，其实刚好到2018年2月20日的凌晨就到期了"
                show-icon
                style="margin-bottom: 10px;">
        </el-alert>

        <!--TAble-->
        <el-table :data="ActIty" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="title" label="标题"></el-table-column>
            <el-table-column prop="mainImg" label='图片'>
                <template slot-scope='scope'>
                    <img v-if="scope.row.mainImg && scope.row.mainImg.path" :src='scope.row.mainImg.path'
                         class="mainImg">
                    <span v-else>暂未有图片</span>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="80">
                <template slot-scope='scope'>
                    <span v-if="scope.row.type === 0">默认</span>
                    <span v-else="scope.row.type === 1">打开URL</span>
                </template>
            </el-table-column>
            <el-table-column prop="valid" label="有效期">
                <template slot-scope='scope'>
                    <span v-if="scope.row.valid === null">无</span>
                    <span v-else-if="scope.row.valid === 0">自定义</span>
                    <span v-else="scope.row.valid === 1">永久有效</span>
                </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间">
                <template slot-scope='scope'>
                    <span v-if="scope.row.startTime">{{scope.row.startTime | formatDate}}</span>
                    <span v-else style="color: red">无时间</span>
                </template>
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间">
                <template slot-scope='scope'>
                    <span v-if="scope.row.endTime">{{scope.row.endTime | formatDate}}</span>
                    <span v-else style="color: red">无时间</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-col :span="24" class="toolbar">
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="size"
                           :total="total" style="float:right;"></el-pagination>
        </el-col>

        <!--编辑-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false" top="5%" size="large">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动类型" prop="type">
                    <el-select v-model="editForm.type" placeholder="请选择">
                        <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容">
                    <UEditor @ready="editorReadyEdit"></UEditor>
                    <!--<el-input v-model="editForm.body"></el-input>-->
                </el-form-item>
                <el-form-item label="url地址" prop="url">
                    <el-input v-model="editForm.url" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="展示图片" prop="mainImg">
                    <el-upload class="avatar-uploader" :action="$store.state.imagesUrl + 'api/common/file/upload/image'"
                               :show-file-list="false" :on-success="handleAvatarSuccess1"
                               :before-upload="beforeAvatarUpload" :headers="MyHeaders">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="有效期限" prop="valid">
                    <el-select v-model="editForm.valid" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-show="limit" label="选择时间" prop="startTime">
                    <el-date-picker
                            v-model="times"
                            type="daterange"
                            placeholder="选择日期范围" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click="editSubmit('editForm')" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增-->
        <el-dialog title="添加活动" v-model="addFormVisible" :close-on-click-modal="false" top="5%" size="large">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addForm.title" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动类型" prop="type">
                    <el-select v-model="addForm.type" placeholder="请选择">
                        <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容">
                    <UEditor @ready="editorReady" style=""></UEditor>
                    <!--<el-input v-model="addForm.body"></el-input>-->
                </el-form-item>
                <el-form-item label="链接地址" prop="url">
                    <el-input v-model="addForm.url" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="展示图片" prop="mainImg">
                    <el-upload class="avatar-uploader" :action="$store.state.imagesUrl + 'api/common/file/upload/image'"
                               :show-file-list="false" :on-success="handleAvatarSuccess"
                               :before-upload="beforeAvatarUpload" :headers="MyHeaders">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div class="el-upload__tip" slot="tip">图片尺寸：690 X 300</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="有效期限" prop="valid">
                    <el-select v-model="addForm.valid" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-show="limitTwo" label="选择时间" prop="startTime">
                    <el-date-picker
                            v-model="timesTwo"
                            type="daterange"
                            placeholder="选择日期范围" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit('addForm')" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--动态活动展示-->
        <el-dialog
                title="动态活动链接"
                :visible.sync="dynamicShowDialogVisible"
                size="small">
            <el-collapse @change="handleChange">
                <el-collapse-item title="签到有礼" name="1">
                    <div>链接地址：<span v-text="$store.state.siteUrl"></span>wap/app/activity/dynamic/sign</div>
                </el-collapse-item>
                <el-collapse-item title="邀请有礼" name="2">
                    <div>链接地址：<span v-text="$store.state.siteUrl"></span>wap/app/activity/dynamic/invite</div>
                </el-collapse-item>
                <el-collapse-item title="解套" name="3">
                    <div>链接地址：<span v-text="$store.state.siteUrl"></span>wap/app/activity/dynamic/jietao</div>
                </el-collapse-item>
                <el-collapse-item title="证券开户" name="4">
                    <div>链接地址：<span v-text="$store.state.siteUrl"></span>wap/app/activity/dynamic/open</div>
                </el-collapse-item>
            </el-collapse>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dynamicShowDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import util from '../../common/js/util';
    import {activityList, activityDel, activityNew, activityEdit} from '../../api/api';
    import {formatDate} from '../../common/js/formatDate';
    import UEditor from '../../components/ueditor/index';
    export default {
        data() {
            return {
                typeOptions: [{
                    value: 0,
                    label: '默认'
                }, {
                    value: 1,
                    label: '打开url'
                }],
                options: [{
                    value: 0,
                    label: '时间选择'
                }, {
                    value: 1,
                    label: '永久有效'
                }],
                ActIty: [],
                total: 0,
                page: 1,
                size: 15,
                ActData: {
                    id: null,
                    title: ''
                },
                listLoading: false,
                sels: [],
                times: '',
                timesTwo: '',
                /*编辑界面*/
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                limit: false,
                editFormRules: {
                    title: {required: true, message: '请输入标题', trigger: 'blur'},
                },
                ueEdit: null,
                //编辑界面数据
                editForm: {
                    id: null,
                    title: '',
                    url:'',
                    type:0,
                    valid: null,
                    startTime: '',
                    endTime: '',
                    mainImg: {
                        path: ''
                    }
                },
                /*新增界面*/
                addFormVisible: false,
                addLoading: false,
                limitTwo: true,
                addFormRules: {
                    title: {required: true, message: '请输入标题', trigger: 'blur'},
                },
                MyHeaders: {'X-Authentication': JSON.parse(sessionStorage.getItem('user'))},
                imageUrl: '',
                /*新增界面数据*/
                addForm: {
                    title: '',
                    url:'',
                    type:0,
                    valid: 0,
                    startTime: '',
                    endTime: '',
                    mainImg: {
                        path: ''
                    }
                },
                ueAdd: null,
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                dynamicShowDialogVisible:false,//展示动态的活动连接
            }
        },
        methods: {
            editorReady (editorInstance) {
                this.ueAdd = editorInstance;
                editorInstance.setContent('');
                editorInstance.addListener('contentChange', () => {
                    console.log('内容发生了变化：', editorInstance.getContent());
                });
            },
            editorReadyEdit (editorInstance) {
                this.ueEdit = editorInstance;
                editorInstance.setContent('');
                editorInstance.addListener('contentChange', () => {
                    console.log('内容发生了变化：', editorInstance.getContent());
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getActivity();
            },
            getActivity() {
                let para = {
                    page: this.page,
                    size: this.size,
                    data: this.ActData
                };
                this.listLoading = true;
                activityList(para).then((res) => {
                    this.listLoading = false;
                    let {code, data} = res;
                    if (code !== 20000) {
                        this.$message({message: res.message, type: 'error'});
                    } else {
                        this.ActIty = data.content;
                        this.total = data.totalElements;
                    }
                });
            },
            /*删除*/
            handleDel(index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = {id: row.id};
                    let id = row.id;
                    activityDel(id, para).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: res.message,
                            type: 'success'
                        });
                        this.getActivity();
                    });
                }).catch(() => {
                });
            },
            /*显示编辑界面*/
            handleEdit(index, row) {
                console.log(row);
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
                if (row.mainImg === null) {
                    this.imageUrl = '';
                    this.editForm.mainImg = {
                        path: ''
                    }
                } else {
                    this.imageUrl = row.mainImg.path;
                }
                this.times = [new Date(row.startTime), new Date(row.endTime)];
                if(row.valid === 1){this.times = []}
                var time = setInterval(() => {
                    if(this.ueEdit!==null){
                        this.ueEdit.setContent(row.body);
                        clearInterval(time);
                    }
                },100)
            },
            /*上传*/
            handleAvatarSuccess(res, file) {
                this.imageUrl = file.response.data.pathFull;
                this.addForm.mainImg.path = file.response.data.path;
            },
            handleAvatarSuccess1(res, file) {
                this.imageUrl = file.response.data.pathFull;
                this.editForm.mainImg.path = file.response.data.path;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG/png 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            /*显示新增界面*/
            handleAdd() {
                this.addFormVisible = true;
                this.addForm = {
                    title: '',
                    url:'',
                    type:0,
                    valid: 0,
                    startTime: '',
                    endTime: '',
                    mainImg: {path: ''}
                };
                this.times = '';
                this.imageUrl = '';
                if(this.ueAdd !== null){
                    this.ueAdd.setContent('');
                }
            },
            /*编辑*/
            editSubmit(a) {
                if(this.limit){
                    this.editForm.startTime = (!this.times[0] || this.times[0] == '') ? '' : util.formatDate.format(new Date(this.times[0]), 'yyyy-MM-dd');
                    this.editForm.endTime = (!this.times[1] || this.times[1] == '') ? '' : util.formatDate.format(new Date(this.times[1]), 'yyyy-MM-dd');
                }else{
                    this.editForm.startTime = this.editForm.endTime = '';
                }
                if(this.ueEdit.getContent()===''){this.$message({message: '请填写内容', type: 'error'});return;}
                if(this.editForm.valid === 0 && this.editForm.startTime==='' && this.editForm.endTime==='' ){
                    this.$message({message: '请选择日期', type: 'error'});return;
                }
                this.$refs[a].validate((valid) => {
                    if(valid){
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editFormVisible = true;
                            let para = this.editForm;
                            para.body=this.ueEdit.getContent();
                            if(typeof para.mainImg === 'string'){
                                para.mainImg={};
                            }
                            activityEdit(para).then((res) => {
                                this.editLoading = false;
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.editFormVisible = false;
                                this.getActivity();
                            });
                        });
                    }
                });
            },
            addSubmit(a) {
                if(this.limitTwo){
                    this.addForm.startTime = (!this.timesTwo[0] || this.timesTwo[0] == '') ? '' : util.formatDate.format(new Date(this.timesTwo[0]), 'yyyy-MM-dd');
                    this.addForm.endTime = (!this.timesTwo[1] || this.timesTwo[1] == '') ? '' : util.formatDate.format(new Date(this.timesTwo[1]), 'yyyy-MM-dd');
                }else{
                    this.addForm.endTime = this.addForm.startTime = ''
                }
                if(this.ueAdd.getContent()===''){this.$message({message: '请填写内容', type: 'error'});return;}
                if(this.addForm.valid === 0 && this.addForm.startTime==='' && this.addForm.endTime==='' ){
                    this.$message({message: '请选择日期', type: 'error'});return;
                }
                this.$refs[a].validate((valid) => {
                    if (valid){
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            let para = this.addForm;
                            para.body=this.ueAdd.getContent();
                            if(typeof para.mainImg === 'string'){
                                para.mainImg={};
                            }
                            activityNew(para).then((res) => {
                                this.addLoading = false;
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.addFormVisible = false;
                                this.getActivity();
                            });
                        });
                    }
                });
            }
        },
        filters: {
            formatDate(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd');
            }
        },
        watch: {
            'editForm.valid': function (val, oldVal) {
                if(val === 1){
                    this.limit = false;
                }else{
                    this.limit = true;
                }
            },
            'addForm.valid': function (val, oldVal) {
                if(val === 1){
                    this.limitTwo = false;
                }else{
                    this.limitTwo = true;
                }
            },
        },
        mounted(){
            this.getActivity();
        },
        components:{
            UEditor
        }

    }
</script>
<style type="text/scss" lang="scss" scoped>
    .el-date-editor {
        width: 100%;
        border: 0;
        .el-input__inner {
            padding-right: 10px;
        }
    }
    .adv-text{
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }
    #activity {
        .mainImg {
            width: auto;
            height: 20px;
            vertical-align: middle;
        }
        .avatar-uploader {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            width: 182px;
            &:hover {
                border-color: #20a0ff;
            }
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    }
</style>